import org.apache.commons.lang3.ArrayUtils
import javax.servlet.http.HttpServletRequest

/**
 * 获得当前用户的IP地址
 */
fun HttpServletRequest.getRealIp(): String = this.getRealIp("")

fun HttpServletRequest.getRealIp(defaultIP: String): String {

    var ip: String?
    ip = this.getHeader("X-Forwarded-For")
    if (ip == null || ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
        ip = this.getHeader("Proxy-Client-IP")
    }
    if (ip == null || ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
        ip = this.getHeader("WL-Proxy-Client-IP")
    }
    if (ip == null || ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
        ip = this.getHeader("HTTP_CLIENT_IP")
    }
    if (ip == null || ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
        ip = this.getHeader("HTTP_X_FORWARDED_FOR")
    }
    if (ip == null || ip.isEmpty() || "unknown".equals(ip, ignoreCase = true)) {
        ip = this.remoteAddr
    }
    if (ArrayUtils.contains("0:0:0:0:0:0:0:1,::1".split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray(), ip)) {
        ip = "127.0.0.1"
    }
    return ip ?: defaultIP
}

/**
 * 获得当前用户的浏览器UA
 */
fun HttpServletRequest.getUserAgent(): String {
    val header: String? = this.getHeader("User-Agent")
    return header ?: ""
}

/**
 * 获得当前访问的来源
 */
fun HttpServletRequest.getReferer(): String = this.getReferer("")

fun HttpServletRequest.getReferer(defaultReferer: String): String {
    val header: String? = this.getHeader("Referer")
    return header ?: defaultReferer
}

/**
 * 判断是否为Ajax异步提交
 */
fun HttpServletRequest.isAjax(): Boolean {
    val header: String? = this.getHeader("X-Requested-With")
    if (header != null && "XMLHttpRequest".equals(header, ignoreCase = true)) {
        return true
    }
    return false
}

fun HttpServletRequest.getAttributeToBoolean(key: String): Boolean {
    val obj = this.getAttribute(key)
    if (obj is Boolean) {
        return obj
    }
    return false
}

fun HttpServletRequest.getAttributeToString(key: String): String {
    val obj = this.getAttribute(key)
    if (obj is String) {
        return obj
    }
    return ""
}
